
package vv.lines.view.swing.animation;

import vv.lines.core.Ball;
import vv.lines.core.Cell;
import vv.lines.core.animations.AbstractAnimation;
import vv.lines.core.animations.AnimationType;

import java.util.List;

import static vv.lines.view.swing.utils.SwingLinesConstants.DISTANCE_STEP;

/**
 *
 * @author vpotapenko
 */
public class SwingMoveAnimation extends AbstractAnimation {

    private double distance = 0;

    private Cell source;

    public boolean hasAnimation() {
        return source != null;
    }

    private boolean hasNextSource() {
        List<Cell> path = getCells();
        return path != null && path.size() > 1;
    }

    @Override
    protected void updateAnimationState() {
        if (distance >= 1) {
            nextSource();
        } else {
            distance += DISTANCE_STEP;
        }
    }

    private void nextSource() {
        List<Cell> path = getCells();
        source = hasNextSource() ? path.remove(0) : null;
        
        if (source != null) distance = 0;
    }

    protected void updateView() {
        Cell target = getCells().get(0);
        int x = (int) (source.getX() + distance * (target.getX() - source.getX()));
        int y = (int) (source.getY() + distance * (target.getY() - source.getY()));

        Ball ball = getTarget().iterator().next();
        ball.setLocation(x, y);
        ball.setSize(target.getWidth(), target.getHeight());
    }

    public AnimationType getType() {
        return AnimationType.MOVE;
    }

    @Override
    public void setCells(List<Cell> cells) {
        super.setCells(cells);
        nextSource();
    }
}
